#_*_ coding: utf-8 _*_
__author__ = "Abraham"
__date__ = '2019/2/27 9:20 PM'



# websocket_server 服务器端；
import asyncio   #异步IO
from ws4py.server.tulipserver import *
from ws4py.async_websocket import WebSocket
from socket import *
import sys
from threading import *
from queue import Queue
import websockets
import asyncio
q=Queue()
lis = list()
def get_data(data):
    print("*/*/*/*/*/*/*/*//*/*////*///",data)
    with open('warning.txt','a') as f:
        f.write(data)
        f.write('\n')

def recv_data():
    with open('warning.txt','r+') as f:
        data = f.readline()
    with open('warning.txt','w+') as f:
        line = f.readlines()
        line[0]=""
        f.writelines(line[0])
    return data
# 获取EventLoop:
loop = asyncio.get_event_loop()
class WsServer(WebSocket):
    clients = set()
    print("**")
    # m = q.get()
    # print("send msg..." + m)

    # 添加链接的webseocket client
    def opened(self):
        print("new connection...")
        self.clients.add(self)
        print(self.clients)

    # 向网页客户端发送数据
    def received_message(self,m):


        with open('warning.txt', 'r') as f:
            m = f.readline()
            print("send msg..." + m)
            if m:
                for client in self.clients:
                    client.send(m)
                    break
        with open('warning.txt','r+') as f:
            files = f.readlines()
        files[0] = ''
        with open('warning.txt', 'r+') as f:
            f.writelines(files)


        # with open('warning.txt', 'r') as f:
        #     line = f.readlines()
        #     del line[0]

    # 断开链接
    def closed(self, code, reason="Error"):
        print("connect close...")


def init_server(host, port):
    factory = lambda: WebSocketProtocol(WsServer)
    print("factory = ", factory)
    return loop.create_server(factory, host, port)


#
def main():
    # 执行coroutine 生成ws server 对象
    ws_server = loop.run_until_complete(init_server('localhost', 9000))
    print('serving on', ws_server.sockets[0].getsockname())
    loop.run_forever()

if __name__ == '__main__':
    # recv_data = recv_data()
    # recv_data.run()
    main()



